package com.gosdk.p;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.gosdk.p.vo.Offer;
import com.gosdk.p.vo.OfferConfigManager;

public class HttpUtils {

    private static String HOST = "http://api.fxnetwork888.com:8080/pushapi/";

    final private static String API_URL_USERINFO_OFFER = "offerlist.do";
    final private static String API_URL_LOG = "pushlog.do";

    public static void sendLog(Context context, String type, Offer offer) {
        Log.d("sdk", "sss");
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (tm == null) {
                return;
            }
            String deviceid = tm.getDeviceId();

            PackageManager manager = context.getPackageManager();
            ApplicationInfo appinfo = manager.getApplicationInfo(context.getPackageName(), 128);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("device", deviceid));
            params.add(new BasicNameValuePair("app", context.getPackageName()));
            params.add(new BasicNameValuePair("offer", offer.getId()));
            params.add(new BasicNameValuePair("type", type));
            params.add(new BasicNameValuePair("package", offer.getPackagename()));
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST + API_URL_LOG);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                Log.d("sdk", EntityUtils.toString(httpResponse.getEntity(), "UTF-8"));
            }
            Log.d("sdk", "zzz");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("sdk", "aaa");
        }
    }

    public static List<Offer> requestUserOffers(Context context) throws Exception {

        List<Offer> offers = new ArrayList<Offer>();

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return null;
        }
        String deviceid = tm.getDeviceId();

        PackageManager manager = context.getPackageManager();
        ApplicationInfo appinfo = manager.getApplicationInfo(context.getPackageName(), 128);

        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("device", deviceid));
            params.add(new BasicNameValuePair("packagename", context.getPackageName()));
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            final HttpPost post = new HttpPost(HOST + API_URL_USERINFO_OFFER);
            post.setEntity(entity);

            HttpResponse httpResponse = getHttpClient().execute(post);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                JSONObject responseJson = getJsonObject(httpResponse);

                OfferConfigManager.updateImpressionInterval(context, responseJson.getInt("interval"));
                OfferConfigManager.updateRequestServerInterval(context, responseJson.getInt("request_interval"));
                OfferConfigManager.updateAdStatus(context, responseJson.getString("ad_close").equals("1") ? true : false);
                OfferConfigManager.updateClickRate(context, responseJson.getInt("c_rate"));

                JSONObject offerArray = responseJson.getJSONObject("list");

                if (offerArray != null) {
                    Iterator<String> keys = offerArray.keys();

                    while (keys.hasNext()) {
                        String offerid = keys.next();
                        JSONObject item = offerArray.getJSONObject(offerid);
                        Offer offer = new Offer();
                        offer.setId(offerid);
                        offer.setContent(item.getString("content"));
                        offer.setName(item.getString("name"));
                        offer.setOrder(item.getString("order"));
                        offer.setPackagename(item.getString("packagename"));
                        offer.setType(item.getString("type"));
                        offer.setUrl(item.getString("url"));
                        offers.add(offer);
                    }
                }

                Collections.sort(offers);

                OfferConfigManager.updateOfferList(context, offers);
            }
        } catch (Exception e) {

            e.printStackTrace();
            // TODO Auto-generated catch block
            throw new Exception();

        }

        return offers;
    }

    private static JSONObject getJsonObject(HttpResponse httpResponse) throws Exception {
        String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        JSONObject responseJson = new JSONObject(response);
        return responseJson;
    }

    /**
     * Configures the httpClient to connect to the URL provided.
     */
    public static HttpClient getHttpClient() {
        HttpClient httpClient = new DefaultHttpClient();

        final HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 5000);

        return httpClient;
    }
}
